package com.hk.commons.domain.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * Created by Antinomy on 15/9/10.
 */
public class JsonService {
    public static String readValue(String jsonString, String readTarget) {

        String[] chain = readTarget.split("\\.");
        JSONObject json = JSON.parseObject(jsonString);

        JSONObject lastLeaf = getLast(json, chain);

        String subestKey = chain[chain.length - 1];
        return lastLeaf.getString(subestKey);
    }

    private static JSONObject getLast(JSONObject json, String[] chain) {
        int size = chain.length;

        return loopToLast(json, size, chain, 0);
    }

    private static JSONObject loopToLast(JSONObject json, int size, String[] chain, int index) {
        if (size == 1)
            return json;

        String node = chain[index];
        JSONObject next = null;

        Object obj = json.getObject(node, Object.class);

        if (obj instanceof JSONArray) {
            JSONArray sub = json.getJSONArray(node);
            next = sub.getJSONObject(0);
        } else {
            next= json.getJSONObject(node);
        }

        size = size - 1;
        index = index + 1;

        return loopToLast(next, size, chain, index);
    }
}
